<?php
require_once 'BlogArticleCategoryLink.php';

/**
 *  zend db table
 */
class Application_Model_DbTable_BlogArticleCategoryLinks extends Zend_Db_Table_Abstract
{
    protected $_name = 'ap_blog_article_category_link';
}


/**
 *  
 */
class BlogArticleCategoryLinks extends BaseMapper
{
    protected $_modelName   = 'BlogArticleCategoryLink';
    protected $_dbTableName = 'Application_Model_DbTable_BlogArticleCategoryLinks';

    /* ================================================================================
        about model object
    ================================================================================ */

    /**
     *  set mapRow by pure database record
     */
    public function mapRow($row)
    {

        $model = $this->getModel();
        $model->setId                   ( $row['id']                   );
        $model->setUserId               ( $row['user_id']              );
        $model->setBlogId               ( $row['blog_id']              );
        $model->setArticleId            ( $row['article_id']           );
        $model->setCategoryId           ( $row['category_id']          );
        return $model;
    }

    /* ================================================================================
        write database
    ================================================================================ */

    /**
     *  add
     */
    public function addBlogArticleCategoryLink( $model )
    {
        return $this->_save( $model, 'add' );
    }

    /**
     *  update
     */
    public function updateBlogArticleCategoryLink( $model )
    {
        return $this->_save( $model, 'update' );
    }

    /* ================================================================================
        access database
    ================================================================================ */

    /**
     *  get
     */
    public function getBlogArticleCategoryLink( $id, $userId=null )
    {
        $model = $this->_find($id);
        if( $userId && $model->getUserId() != $userId ) {
            return false;
        }
        return $model;
    }

    /**
     *  get many
     */
    public function getBlogArticleCategoryLinks( $userId=null, $blogId=null, $categoryId=null, $page=null, $rowCount=null ) 
    {
        if( null===$page ) {
            $page = 1;
        }
        if( null===$rowCount ) {
            $rowCount = BaseMapper::DEFAULT_ROW_COUNT;
        }

        $opt = Array(
            'userId'     => $userId,
            'blogId'     => $blogId,
            'categoryId' => $categoryId,
            '_orderBy'   => ' id DESC ',
            '_page'      => $page,
            '_rowCount'  => $rowCount,
        );
        return $this->_getByQuery($opt);
    }

    /**
     *  get count by "getBlogArticleCategoryLinks" method
     */
    public function getNumBlogArticleCategoryLinks() 
    {
        $opt = Array(
            'userId'     => $userId,
            'blogId'     => $blogId,
            'categoryId' => $categoryId,
        );
        return $this->_getByQuery($opt,true);
    }

    /**
     *  get query
     */
    protected function _getByQuery( $opt, $isGetTotal=false )
    {
        $this->_checkOption($opt);
        $opt += Array(
            'id'                   => (isset($opt['id'])                   ? (int) ($opt['id'])                   : NULL ),
            'userId'               => (isset($opt['userId'])               ? (int) ($opt['userId'])               : NULL ),
            'blogId'               => (isset($opt['blogId'])               ? (int) ($opt['blogId'])               : NULL ),
            'articleId'            => (isset($opt['articleId'])            ? (int) ($opt['articleId'])            : NULL ),
            'categoryId'           => (isset($opt['categoryId'])           ? (int) ($opt['categoryId'])           : NULL ),
            '_orderBy'             => (isset($opt['_orderBy'])             ?       ($opt['_orderBy'])             : ' id DESC ' ),
            '_page'                => (isset($opt['_page'])                ? (int) ($opt['_page'])                : 1 ),
            '_rowCount'            => (isset($opt['_rowCount'])            ? (int) ($opt['_rowCount'])            : BaseMapper::DEFAULT_ROW_COUNT ),
        );

        if( isset($opt['_orderBy']) ) {
            $opt['_orderBy'] = explode(',',$opt['_orderBy']);
        }

        if( isset($opt['_page']) && $opt['_page']<=1 ) {
            $opt['_page'] = 1;
        }

        $where = Array();
        if(isset( $opt['id']                  )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' id = ? '                  , $opt['id']                   );  }
        if(isset( $opt['userId']              )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' user_id = ? '             , $opt['userId']               );  }
        if(isset( $opt['blogId']              )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' blog_id = ? '             , $opt['blogId']               );  }
        if(isset( $opt['articleId']           )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' article_id = ? '          , $opt['articleId']            );  }
        if(isset( $opt['categoryId']          )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' category_id = ? '         , $opt['categoryId']           );  }

        // where from array to string
        $whereString = join(' AND ',$where);
        if(!$whereString) {
            $whereString = null;
        }

        // get total
        if( $isGetTotal ) {
            $select = $this->getDb()->select();
            $select->from( $this->getDb(), Array('COUNT(*) AS total') );
            if($whereString) {
                $select->where( $whereString );
            }
            $rows = $this->getDb()->fetchRow($select);
            $row = $rows->toArray();
            return (int) $row['total'];
        }

        //
        //echo $whereString;

        //
        if( NULL === $opt['_page'] ) {
            $rowset = $this->getDb()->fetchAll($whereString, $opt['_orderBy']);
        }
        else {
            $offset = ($opt['_page']-1) * $opt['_rowCount'];
            $rowset = $this->getDb()->fetchAll($whereString, $opt['_orderBy'], $opt['_rowCount'], $offset );
        }
        if( !$rowset ) {
            return NULL;
        }

        $models = Array();
        foreach( $rowset as $row ) {
            $models[] = $this->mapRow( $row->toArray() );
        }
        return $models;

    }

}

